<template>
  <div id="index" ref="appRef">
    <div class="bg">
      <dv-loading v-if="loading">Loading...</dv-loading>
      <!-- 第一行 标题-->
      <div v-else class="host-body">
        <div class="d-flex jc-center">
          <div>
            <dv-decoration-10 class="dv-dec-10" />
            <div class="react-left">
                <span class="text">
                  请选择对应的节点进行登录
                </span>
            </div>
          </div>
          <div class="d-flex jc-center">
            <dv-decoration-8 class="dv-dec-8" :color="['#568aea', '#000000']" />
            <div class="title">
              <span class="title-text">{{ title }}</span>
              <dv-decoration-6
                class="dv-dec-6"
                :reverse="true"
                :color="['#50e3c2', '#67a1e5']"
              />
            </div>
            <dv-decoration-8
              class="dv-dec-8"
              :reverse="true"
              :color="['#568aea', '#000000']"
            />
          </div>
          <div>
            <dv-decoration-10 class="dv-dec-10" />
            <div class="react-right">
              <span class="text">
                {{ timeInfo.dateYear }}
                {{ timeInfo.dateDay }}
                {{ timeInfo.dateWeek }}
              </span>
              <div class="text">
                <a-button type="primary" size="small" @click="toLogin()" >
                  <template #icon><PoweroffOutlined /></template>
                  登录
                </a-button>
              </div>
            </div>
          </div>
        </div>
        <div class="body-box">
          <echarts-map-nodes :nodes="nodes"/>
        </div>
      </div>
    </div>
  </div>
  <!-- 登录弹窗 -->
  <div class="login" v-if="showLogin">
    <div class="login-form">
      <div class="login-div" v-if="node.name">
        <h2 v-if="node.name">当前访问 {{ node.name}}</h2>
        <span v-if="node.ip">IP地址：{{node.ip}}</span>
      </div>
      <div class="login-div">
        <input class="login-input" type="text" placeholder="用户名" v-model="username" name="user"  >
      </div>
      <div class="login-div">
        <input class="login-input" type="password" placeholder="密码" v-model="password" name="pwd" @keyup.enter="login()">
      </div>
      <div class="login-div">
        <button style=" background-color:#4CAF50;"  @click="login()" >登录</button> <button style=" background-color:#5f5f5f;"  @click="closeLogin()" >关闭</button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  onBeforeUnmount, toRefs,
} from 'vue'
import { PoweroffOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import md5 from "js-md5";
import { formatTime } from '@/utils'
import { title, subtitle, WEEK } from '@/constant'
import useDraw from '@/utils/useDraw'
import EchartsMapNodes from '@/views/echarts/map/nodes/index.vue'
import {api} from "@/axios/api";
import { StorageLocal,StorageSession } from "@/storage/storage";
import {useRouter} from "vue-router";

export default defineComponent({
  components: {
    PoweroffOutlined,
    EchartsMapNodes,
  },
  setup() {
    const router = useRouter();
    // * 加载标识
    const loading = ref<boolean>(true)
    // * 时间内容
    const timeInfo = reactive({
      setInterval: 0,
      dateDay: '',
      dateYear: '',
      dateWeek: ''
    })
    // * 适配处理
    const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw()

    // methods
    // todo 处理 loading 展示
    const cancelLoading = () => {
      setTimeout(() => {
        loading.value = false
      }, 500)
    }

    // todo 处理时间监听
    const handleTime = () => {
      timeInfo.setInterval = setInterval(() => {
        const date = new Date()
        timeInfo.dateDay = formatTime(date, 'HH: mm: ss')
        timeInfo.dateYear = formatTime(date, 'yyyy-MM-dd')
        timeInfo.dateWeek = WEEK[date.getDay()]
      }, 1000)
    }
    /***********************************************/
    const timerInterval = reactive({
      interval: 0,
      times: 600000,
    })

    // 定义响应式数据 data
    const state= reactive({
      showLogin : false,
      node : {name:"",ip:""},
      username:"",
      password:"",
      nodes: [],
      count: [0,0,0,0],
    });
    // 定义方法
    const methods = {
      async changeTiming() {
        timerInterval.interval = setInterval(() => {
          //methods.initNodes()
        }, timerInterval.times)
      }, toLogin ()  {
        if(state.nodes.length>0){
          const node:any = StorageSession.get('node')
          if(node && node.name && node.ip){
            state.showLogin = true
            state.node = node
          }else{
            state.showLogin = false
            message.config({
              top: `300px`,
              duration: 3,
              maxCount: 1
            });
            message.warning({
              content: () => '请先选择节点（点击节点），再进行登录！',
              class: 'warn-message',
              style: {
                marginTop: '20vh',
              },
            });
          }
        }else{
          state.showLogin = false
        }
      },closeLogin(){
        state.showLogin = false
      },login(){
        state.showLogin = false
        // 第二个参数是表示自动关闭的延时，单位秒。设为 0 时不自动关闭。
        const loadingMessage = message.loading('正在登录，请稍后！', 5);
        // 请求服务器拉取数据 96e79218965eb72c92a549dd5a330112
        api.nidtga.login({username: state.username, password: md5(state.password)}).then((res: any) => {
          loadingMessage();
          if (res) {
            if (res.data && res.data.code === 0) {
              if (res.data.msg) {
                // 等待api请求成功后，执行关闭
                StorageSession.set('token', res.data.msg)
                // 清空密码
                state.password = '';
                setTimeout(function(){
                  // 跳转页面
                  router.push({path:'/node',"params":{}})
                },1000);
              }else{
                message.error('登录失败，请联系管理员！');
              }
            }else if(res.data.code === 500){
              let msg = '用户不存在，请联系管理员！'
              if(res.data.msg){
                msg =res.data.msg
              }
              message.error(msg);
            } else{
              message.error('登录失败，请联系管理员！');
            }
          } else{
            message.error('无法链接服务器，请联系管理员！');
          }
        })
      },
        async refreshNodeData(){
          await api.nodes.nodes().then((res: any) => {
            if(res){
              if (res.data && res.data.code === 0) {
                if (res.data.rows && res.data.rows.length >0) {
                  state.nodes=res.data.rows
                }
              }else{
                // 需要登录
                state.showLogin = true
              }
            }else{
              // 需要登录
              state.showLogin = true
            }

          })
        },
        async nodeCount ()  {
          if(state.nodes.length>0){
            state.count = [0,0,0,0]
            let num = state.nodes.length;
            //console.log("num:"+num)
            let i = 0;
            while (num){
              if(i<4){
                state.count[i]=Math.floor(num % 10);
              }else{
                state.count.push(Math.floor(num % 10))
              }
              i++;
              num =  Math.floor(num /10)
            }
            // 倒序排序
            state.count.reverse()
          }
        },

      }
    // 生命周期
    onMounted(() => {
      cancelLoading()
      handleTime()
      // todo 屏幕适应
      windowDraw()
      calcRate()
      const token = StorageSession.get('token')
      if (!token){
        state.showLogin = true
      }else{
        setTimeout(function(){
          methods.refreshNodeData()
        },1000);
      }
      methods.changeTiming()
    })

    onBeforeUnmount(() => {
      unWindowDraw()
      clearInterval(timeInfo.setInterval)
    })


    // return
    return {
      loading,
      timeInfo,
      appRef,
      title,
      subtitle,
      ...toRefs(state),
      ...methods,
    }
  }
})
</script>

<style lang="scss" scoped>
@import '@/assets/scss/index.scss';
body {
  text-align: center;
}
.login {
  text-align: center;
  background-color: burlywood;
}
.login-form {
  font-family: 微软雅黑;
  position: fixed;
  background-color: white;
  top: 35%;
  left: 35%;
  width: 500px;
  border-radius: 1em;
  text-align: center;
  z-index: 999;
}
.login-input {
  text-align: center;
  border-radius: 0.2em;
  width: 380px;
  height: 45px;
  border: none;
  background-color:#f2f2f2;
  font-size: 28px;
  color: #0f1325;
}
.login-input::-webkit-input-placeholder {
  font-size: 26px;
}
.login-div {
  position: relative;
  margin-top: 40px;
}

.login-div button {
  cursor: pointer;
  color: white;
  font-size: 26px;
  border: none;
  border-radius: 0.4em;
  width: 150px;
  height: 45px;
  margin: 20px;/** 上右下左 **/
}


.warn-message {
  color: red;
}
</style>
